<template>
  <div class="all">

    <div class="picker-item" :style="pickerItemStyle">

      <div class="picker-bar" :style="pickerBarStyle"></div>

      <scroller class="picker-item-list" show-scrollbar="false" :ref="col_1_ref" scroll-direction="vertical"
        :style="pickerItemStyle" @scroll="onScroll" @scrollend="e => scrollEnd(e, col_1_ref)">

        <text @disappear="e => disAppearPickItem(e, col_1_ref, 0)" @appear="e => appearPickItem(e, col_1_ref, 0)"
          :ref="col_1_ref + '_text_0'" class="picker-item-text" :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_1_ref, 1)" @appear="e => appearPickItem(e, col_1_ref, 1)"
          :ref="col_1_ref + '_text_1'" class="picker-item-text" :style="pickerItemTextStyle"></text>

        <text @disappear="e => disAppearPickItem(e, col_1_ref, index + 2)"
          @appear="e => appearPickItem(e, col_1_ref, index + 2)" :ref="col_1_ref + '_text_' + numAdd(index,2)"
          @click="e=> clickScrollerItem(e, col_1_ref, index)" v-for="(item, index) of col_1_list"
          :key="col_1_ref + '_' + index" class="picker-item-text" :style="pickerItemTextStyle">{{ (item.title || '') }}
        </text>

        <text @disappear="e => disAppearPickItem(e, col_1_ref, col_1_list.length - 1 + 3)"
          @appear="e => appearPickItem(e, col_1_ref, col_1_list.length - 1 + 3)"
          :ref="col_1_ref + '_text_' + numAdd(col_1_list.length - 1 + 3)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_1_ref, col_1_list.length - 1 + 4)"
          @appear="e => appearPickItem(e, col_1_ref, col_1_list.length - 1 + 4)"
          :ref="col_1_ref + '_text_' + numAdd(col_1_list.length - 1 + 4)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>

      </scroller>

    </div>

    <div class="picker-item" :style="pickerItemStyle">

      <div class="picker-bar" :style="pickerBarStyle"></div>

      <scroller class="picker-item-list" show-scrollbar="false" :ref="col_2_ref" scroll-direction="vertical"
        :style="pickerItemStyle" @scroll="onScroll" @scrollend="e => scrollEnd(e, col_2_ref)">

        <text @disappear="e => disAppearPickItem(e, col_2_ref, 0)" @appear="e => appearPickItem(e, col_2_ref, 0)"
          :ref="col_2_ref + '_text_0'" class="picker-item-text" :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_2_ref, 1)" @appear="e => appearPickItem(e, col_2_ref, 1)"
          :ref="col_2_ref + '_text_1'" class="picker-item-text" :style="pickerItemTextStyle"></text>

        <text @disappear="e => disAppearPickItem(e, col_2_ref, index + 2)"
          @appear="e => appearPickItem(e, col_2_ref, index + 2)" :ref="col_2_ref + '_text_' + numAdd(index,2)"
          @click="e=> clickScrollerItem(e, col_2_ref, index)" v-for="(item, index) of col_2_list"
          :key="col_2_ref + '_' + index" class="picker-item-text" :style="pickerItemTextStyle">{{ (item.title || '') }}
        </text>

        <text @disappear="e => disAppearPickItem(e, col_2_ref, col_2_list.length - 1 + 3)"
          @appear="e => appearPickItem(e, col_2_ref, col_2_list.length - 1 + 3)"
          :ref="col_2_ref + '_text_' + numAdd(col_2_list.length - 1 + 3)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_2_ref, col_2_list.length - 1 + 4)"
          @appear="e => appearPickItem(e, col_2_ref, col_2_list.length - 1 + 4)"
          :ref="col_2_ref + '_text_' + numAdd(col_2_list.length - 1 + 4)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>

      </scroller>

    </div>

    <div class="picker-item" :style="pickerItemStyle">

      <div class="picker-bar" :style="pickerBarStyle"></div>

      <scroller class="picker-item-list" show-scrollbar="false" :ref="col_3_ref" scroll-direction="vertical"
        :style="pickerItemStyle" @scroll="onScroll" @scrollend="e => scrollEnd(e, col_3_ref)">

        <text @disappear="e => disAppearPickItem(e, col_3_ref, 0)" @appear="e => appearPickItem(e, col_3_ref, 0)"
          :ref="col_3_ref + '_text_0'" class="picker-item-text" :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_3_ref, 1)" @appear="e => appearPickItem(e, col_3_ref, 1)"
          :ref="col_3_ref + '_text_1'" class="picker-item-text" :style="pickerItemTextStyle"></text>

        <text @disappear="e => disAppearPickItem(e, col_3_ref, index + 2)"
          @appear="e => appearPickItem(e, col_3_ref, index + 2)" :ref="col_3_ref + '_text_' + numAdd(index,2)"
          @click="e=> clickScrollerItem(e, col_3_ref, index)" v-for="(item, index) of col_3_list"
          :key="col_3_ref + '_' + index" class="picker-item-text" :style="pickerItemTextStyle">{{ (item.title || '') }}
        </text>

        <text @disappear="e => disAppearPickItem(e, col_3_ref, col_3_list.length - 1 + 3)"
          @appear="e => appearPickItem(e, col_3_ref, col_3_list.length - 1 + 3)"
          :ref="col_3_ref + '_text_' + numAdd(col_3_list.length - 1 + 3)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>
        <text @disappear="e => disAppearPickItem(e, col_3_ref, col_3_list.length - 1 + 4)"
          @appear="e => appearPickItem(e, col_3_ref, col_3_list.length - 1 + 4)"
          :ref="col_3_ref + '_text_' + numAdd(col_3_list.length - 1 + 4)" class="picker-item-text"
          :style="pickerItemTextStyle"></text>

      </scroller>

    </div>

  </div>
</template>

<script>
  import dateUtils from "./dateutils";
  const dom = weex.requireModule("dom");
  import jdebug from "@/_js/debug";

  export default {
    name: "date-view",
    data: () => ({
      pickerWidth: 750,

      pickerHeight: 450,

      pickerBarHeight: 90,

      pickerItemTextHeight: 90,

      column: 3,

      col_1_ref: "picker_col_1",

      col_2_ref: "picker_col_2",

      col_3_ref: "picker_col_3",

      col_1_list: [],

      col_2_list: [],

      col_3_list: [],

      checked_col_1: 0,

      checked_col_2: 0,

      checked_col_3: 0,

      ready: false,

      // 结束标志
      picker_end: false,
      isScrollingByCode: false,
    }),
    props: {
      yearSection: {
        type: Array,
        default: () => [2025, 2050],
      },
      curDate: {
        type: String,
        default: "",
      },
      // 主题色
      themeColor: {
        type: String,
        default: "#2F364B",
      },
      // 选项字体的颜色
      itemFontColor: {
        type: String,
        default: "#E0E7FD",
      },
    },
    created() {
      this.ready = false;
      this.initColumns();
      this.picker_end = false;
    },
    computed: {
      pickerItemStyle() {
        var style = {};
        var width = this.pickerWidth / this.column;
        style["width"] = width + "px";
        return style;
      },
      pickerItemTextStyle() {
        var style = {};
        var width = this.pickerWidth / this.column;
        style["width"] = width + "px";
        style["color"] = this.itemFontColor;
        return style;
      },
      pickerBarStyle() {
        var style = {};

        var margin = 0;
        var width = this.pickerWidth / this.column - margin * 2;
        var top = this.pickerHeight / 2 - this.pickerBarHeight / 2;
        style["width"] = width + "px";
        style["top"] = top + "px";
        style["height"] = this.pickerBarHeight + "px";
        style["marginLeft"] = margin + "px";
        style["marginRight"] = margin + "px";
        style["borderTopColor"] = this.themeColor;
        style["borderBottomColor"] = this.themeColor;
        style["backgroundColor"] = this.themeColor;
        return style;
      },
    },
    mounted() {
      let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
      if (!isIos) {
        setTimeout(() => {
          this.updateCurDate(this.curDate);
        }, 250);
      }
    },
    methods: {
      numAdd(...num) {
        return num.reduce((ret, item) => {
          ret += item;
          return ret;
        }, 0);
      },
      initColumns() {
        if (this.column > 0) {
          this.col_1_list = this.generTimeYear();
          this.checked_col_1 = 0;
        }
        if (this.column > 1) {
          this.col_2_list = this.generTimeMonth();
          this.checked_col_2 = 0;
        }
        if (this.column > 2) {
          this.col_3_list = this.generTimeDate();
          this.checked_col_3 = 0;
        }
        // 初始化列数据
        let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
        if (isIos) {
          this.updateCurDate(this.curDate);
        }
      },
      updateCurDate(newdate) {
        // 计算当前时间
        const date = dateUtils.createDate(newdate);
        const year = date.getFullYear(); // 获取年份
        const month = date.getMonth() + 1; // 获取月份（0-11，需要加1）
        const day = date.getDate(); // 获取日期

        // 根据当前日期设置选中项
        this.checked_col_1 = this.findIndexByTitle(
          this.col_1_list,
          year.toString()
        );
        this.checked_col_2 = this.findIndexByTitle(
          this.col_2_list,
          month > 9 ? month.toString() : "0" + month
        );
        this.checked_col_3 = this.findIndexByTitle(
          this.col_3_list,
          day > 9 ? day.toString() : "0" + day
        );

        // 确保索引合法
        this.checked_col_1 = this.checked_col_1 >= 0 ? this.checked_col_1 : 0;
        this.checked_col_2 = this.checked_col_2 >= 0 ? this.checked_col_2 : 0;
        this.checked_col_3 = this.checked_col_3 >= 0 ? this.checked_col_3 : 0;
        this.refreshColumns();
      },
      refreshColumns() {
        let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
        var _self = this;
        var timer = setTimeout(function () {
          clearTimeout(timer);
          _self.checkedItem(_self.col_1_ref, _self.checked_col_1, !isIos);
          timer = setTimeout(function () {
            clearTimeout(timer);
            _self.checkedItem(_self.col_2_ref, _self.checked_col_2, !isIos);
            timer = setTimeout(function () {
              clearTimeout(timer);
              _self.checkedItem(_self.col_3_ref, _self.checked_col_3, !isIos);
              // 准备完毕
              _self.ready = true;
            }, 30);
          }, 30);
        }, 30);
      },
      onScroll(e) {},

      scrollEnd(e, ref) {
        if (this.picker_end) {
          return;
        }
        // 如果是代码触发的滚动，直接跳过
        let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
        if (this.isScrollingByCode && isIos) {
          jdebug.log("scrollEnd: isScrollingByCode");
          this.isScrollingByCode = false;
          return;
        }

        this.finalSelect(e, ref);
      },

      finalSelect(e, ref) {
        // jdebug.log(
        //   "current checked:" +
        //     this.checked_col_1 +
        //     "-" +
        //     this.checked_col_2 +
        //     "-" +
        //     this.checked_col_3
        // );
        if (this.ready) {
          this.$emit("onChangeDate", {
            year: this.col_1_list[this.checked_col_1].title,
            month: this.col_2_list[this.checked_col_2].title,
            day: this.col_3_list[this.checked_col_3].title,
          });
        }

        var check_col = 0;
        if (this.col_1_ref == ref) {
          check_col = this.checked_col_1;
        } else if (this.col_2_ref == ref) {
          check_col = this.checked_col_2;
        } else if (this.col_3_ref == ref) {
          check_col = this.checked_col_3;
        }

        if (check_col < 0) {
          check_col = 0;
        }
        this.checkedItem(ref, check_col);

        if (this.column > 1) {
          var refarr = ref.split("_");
          var crt_col = parseInt(refarr[2]);

          this.updateOtherCol(crt_col + 1);
        }
      },

      appearPickItem(e, ref, index) {
        if (!e.direction || !this.ready) {
          return;
        }
        var checked_index = index + (e.direction == "down" ? 2 : -2);
        checked_index -= 2;
        if (checked_index < 0) {
          checked_index = 0;
        }

        if (this.col_1_ref == ref) {
          this.checked_col_1 =
            checked_index >= this.col_1_list.length
              ? this.col_1_list.length - 1
              : checked_index;
        } else if (this.col_2_ref == ref) {
          this.checked_col_2 =
            checked_index >= this.col_2_list.length
              ? this.col_2_list.length - 1
              : checked_index;
        } else if (this.col_3_ref == ref) {
          this.checked_col_3 =
            checked_index >= this.col_3_list.length
              ? this.col_3_list.length - 1
              : checked_index;
        }
      },

      disAppearPickItem(e, ref, index) {
        if (!e.direction || !this.ready) {
          return;
        }

        // console.log('disappear ', ref, ' ', index, e.direction)

        var checked_index = index + (e.direction == "up" ? 3 : -3);
        checked_index -= 2;
        if (checked_index < 0) {
          checked_index = 0;
        }

        if (this.col_1_ref == ref) {
          this.checked_col_1 =
            checked_index >= this.col_1_list.length
              ? this.col_1_list.length - 1
              : checked_index;
        } else if (this.col_2_ref == ref) {
          this.checked_col_2 =
            checked_index >= this.col_2_list.length
              ? this.col_2_list.length - 1
              : checked_index;
        } else if (this.col_3_ref == ref) {
          this.checked_col_3 =
            checked_index >= this.col_3_list.length
              ? this.col_3_list.length - 1
              : checked_index;
        }
      },

      // 更新其他列
      updateOtherCol(col) {
        var col_ref = null;

        if (col == 2) {
          col_ref = this.col_2_ref;
          this.col_2_list = this.generTimeMonth();
          this.checked_col_2 = 0;
        } else if (col == 3) {
          col_ref = this.col_3_ref;
          this.col_3_list = this.generTimeDate();
          this.checked_col_3 = 0;
        }
        if (col_ref) {
          this.checkedItem(col_ref, 0);

          if (this.column > col) {
            this.updateOtherCol(col + 1);
          }
        }
      },

      // 选择 某列 某项
      checkedItem(ref, idx, animated = true) {
        if (!ref && idx == null) return;

        const refKey = ref + "_text_" + idx;
        let scrollToItem = this.$refs[refKey];

        if (Array.isArray(scrollToItem)) {
          scrollToItem = scrollToItem.length > 0 ? scrollToItem[0] : null;
        }

        if (!scrollToItem) {
          return;
        }

        // 标记为代码触发的滚动
        this.isScrollingByCode = true;
        dom.scrollToElement(scrollToItem, { animated });
        setTimeout(() => {
          this.isScrollingByCode = false;
        }, 300);
      },

      generTimeYear() {
        var yearSection = this.yearSection;
        var maxYear = Math.max(...yearSection) || new Date().getFullYear();
        var minYear = Math.min(...yearSection) || 1949;
        var dataset = Array.from({ length: maxYear - minYear + 1 }).map(
          (item, index) => {
            return {
              title: maxYear - index + "",
              value: maxYear - index,
            };
          }
        );
        return dataset;
      },
      generTimeMonth() {
        var dataset = Array.from({ length: 12 }).map((item, index) => {
          return {
            title: index + 1 > 9 ? index + 1 + "" : "0" + (index + 1),
            value: index + 1,
          };
        });
        return dataset;
      },
      generTimeDate() {
        var result = this.getResult();
        var values = result.values;
        var year = values[0];
        var month = values[1];
        var dateCount = new Date(year, month, 0).getDate();
        var dataset = Array.from({ length: dateCount }).map((item, index) => {
          return {
            title: index + 1 > 9 ? index + 1 + "" : "0" + (index + 1),
            value: index + 1,
          };
        });
        return dataset;
      },

      findItemByTitle(ref, title) {
        var arr = null;
        if (this.col_1_ref == ref) {
          arr = this.col_1_list;
        } else if (this.col_2_ref == ref) {
          arr = this.col_2_list;
        } else if (this.col_3_ref == ref) {
          arr = this.col_3_list;
        }
        return this.findIndexByTitle(arr, title);
      },

      findIndexByTitle(arr, t) {
        var idx = -1;
        if (!arr) {
          return idx;
        }
        // console.log('find index title ,arr length :', arr.length)
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];
          var title = item.title;
          if (t === title) {
            idx = i;
            break;
          }
        }
        return idx;
      },

      getResult() {
        var rst = {};
        var titles = [];
        var values = [];
        var checked = [];

        if (this.col_1_list.length > 0) {
          if (
            this.checked_col_1 >= 0 &&
            this.checked_col_1 < this.col_1_list.length &&
            this.col_1_list[this.checked_col_1]
          ) {
            var checkobj = Object.assign(
              {},
              this.col_1_list[this.checked_col_1] || {}
            );
            var title = "title" in checkobj ? checkobj.title : "";
            var value = "value" in checkobj ? checkobj.value : title;
            titles.push(title);
            values.push(value);
            checkobj.children && delete checkobj.children;
            checked.push(checkobj);
          } else {
            titles.push(null);
            values.push(null);
            checked.push(null);
          }
        } else {
          titles.push(null);
          values.push(null);
          checked.push(null);
        }

        if (this.column > 1) {
          if (this.col_2_list.length > 0) {
            if (
              this.checked_col_2 >= 0 &&
              this.checked_col_2 < this.col_2_list.length &&
              this.col_2_list[this.checked_col_2]
            ) {
              var checkobj = Object.assign(
                {},
                this.col_2_list[this.checked_col_2] || {}
              );
              var title = "title" in checkobj ? checkobj.title : "";
              var value = "value" in checkobj ? checkobj.value : title;
              titles.push(title);
              values.push(value);
              checkobj.children && delete checkobj.children;
              checked.push(checkobj);
            } else {
              titles.push(null);
              values.push(null);
              checked.push(null);
            }
          } else {
            titles.push(null);
            values.push(null);
            checked.push(null);
          }
        }

        if (this.column > 2) {
          if (this.col_3_list.length > 0) {
            if (
              this.checked_col_3 >= 0 &&
              this.checked_col_3 < this.col_3_list.length &&
              this.col_3_list[this.checked_col_3]
            ) {
              var checkobj = Object.assign(
                {},
                this.col_3_list[this.checked_col_3] || {}
              );
              var title = "title" in checkobj ? checkobj.title : "";
              var value = "value" in checkobj ? checkobj.value : title;
              titles.push(title);
              values.push(value);
              checkobj.children && delete checkobj.children;
              checked.push(checkobj);
            } else {
              titles.push(null);
              values.push(null);
              checked.push(null);
            }
          } else {
            titles.push(null);
            values.push(null);
            checked.push(null);
          }
        }
        rst["titles"] = titles;
        rst["values"] = values;
        rst["title"] = titles.join(" ");
        rst["value"] = values.join(" ");
        rst["checked"] = checked;
        return rst;
      },
      curYear() {
        return this.col_1_list[this.checked_col_1].title;
      },
      curMonth() {
        return this.col_2_list[this.checked_col_2].title;
      },
      curDay() {
        return this.col_3_list[this.checked_col_3].title;
      },

      refreshCheckedByDefaultTitle() {
        var defaultTitle = "";

        var arr = defaultTitle.split(" ");
        if (arr.length > 0) {
          var tidx = this.findItemByTitle(this.col_1_ref, arr[0]);
          this.checked_col_1 = tidx < 0 ? this.checked_col_1 : tidx;
          if (~tidx && arr.length > 1) {
            var tidx = this.findItemByTitle(this.col_2_ref, arr[1]);
            this.checked_col_2 = tidx < 0 ? this.checked_col_2 : tidx;
            if (~tidx && arr.length > 2) {
              var tidx = this.findItemByTitle(this.col_3_ref, arr[2]);
              this.checked_col_3 = tidx < 0 ? this.checked_col_3 : tidx;
            }
          }
        }
      },

      // 点击每个条目时自动选中
      clickScrollerItem(e, ref, idx) {
        if (this.col_1_ref == ref) {
          this.checked_col_1 = idx;
        } else if (this.col_2_ref == ref) {
          this.checked_col_2 = idx;
        } else if (this.col_3_ref == ref) {
          this.checked_col_3 = idx;
        }
        this.finalSelect(e, ref);
      },
    },
  };
</script>

<style scoped>
  .picker-content {
    width: 750px;
    height: 450px;
    flex-direction: row;
  }

  .picker-item {
    position: relative;
    top: 0px;
    height: 450px;
    padding-left: 0px;
    padding-right: 0px;
    padding-top: 0px;
    padding-bottom: 0px;
    overflow-x: hidden;
    overflow-y: scroll;
  }

  .picker-item-list {
    height: 448px; /* 在原来height上减少2px，解决iphone滑到最上面选择了第二个的问题 */
    padding-left: 4px;
    padding-right: 4px;
  }

  .picker-item-text {
    height: 90px;
    line-height: 90px;
    font-size: 32px;
    text-align: center;
    white-space: nowrap;
    color: #e0e7fd;
  }

  .picker-bar {
    position: absolute;
    top: auto;
    border-top-width: 4px;
    border-top-style: solid;
    border-top-color: #2f364b;
    border-bottom-width: 4px;
    border-bottom-style: solid;
    border-bottom-color: #2f364b;
  }
</style>
